import 'package:ad_common/third_ad.dart';
import 'package:flutter/foundation.dart';
import 'package:google_mobile_ads/google_mobile_ads.dart';

import 'google_ad_manager.dart';

/// FileName google_splash_ad
/// @Author zhuqingfang
/// @Date 2022/9/30 5:52 下午
/// @Description google splash ad
class GoogleSplashAd extends ThirdAd {
  GoogleSplashAd({required ThirdAdParams thirdAdParams})
      : super(thirdAdParams: thirdAdParams);
  AppOpenAd? _appOpenAd;

  @override
  void load() {
    if (!isSdkInit) {
      init();
    }
    _loadSplashAd();
  }

  @override
  void show() {
    _showSplashAd();
  }

  void _loadSplashAd() {
    AppOpenAd.load(
      adUnitId: thirdAdParams.placementId,
      orientation: AppOpenAd.orientationPortrait,
      request: const AdRequest(),
      adLoadCallback: AppOpenAdLoadCallback(
        onAdLoaded: (ad) {
          debugPrint('AppOpenAd load Success');
          _appOpenAd = ad;
          thirdAdParams.thirdAdEventCallback(AdCallbackEvent.adLoaded,
              'google splash ad placementID:${thirdAdParams.placementId} loaded');
        },
        onAdFailedToLoad: (error) {
          debugPrint('AppOpenAd failed to load: $error');
          thirdAdParams.thirdAdEventCallback(AdCallbackEvent.adLoadFail,
              'google splash ad placementID:${thirdAdParams.placementId} load fail');
          // Handle the error.
        },
      ),
    );
  }
  void _showSplashAd(){
    if(_appOpenAd == null){
      thirdAdParams.thirdAdEventCallback(AdCallbackEvent.adShowFail,
          'google splash ad placementID:${thirdAdParams.placementId} show fail');
      return;
    }
    _appOpenAd!.fullScreenContentCallback = FullScreenContentCallback(
      onAdShowedFullScreenContent: (ad) {
        debugPrint('$ad onAdShowedFullScreenContent');
        thirdAdParams.thirdAdEventCallback(AdCallbackEvent.adOnShow,
            'google splash ad placementID:${thirdAdParams.placementId} onShow');
      },
      onAdFailedToShowFullScreenContent: (ad, error) {
        debugPrint('$ad onAdFailedToShowFullScreenContent: $error');
        thirdAdParams.thirdAdEventCallback(AdCallbackEvent.adShowFail,
            'google splash ad placementID:${thirdAdParams.placementId} onDismiss');
        ad.dispose();
        _appOpenAd = null;
      },
      onAdDismissedFullScreenContent: (ad) {
        debugPrint('$ad onAdDismissedFullScreenContent');
        thirdAdParams.thirdAdEventCallback(AdCallbackEvent.adOnDismissed,
            'google splash ad placementID:${thirdAdParams.placementId} onDismiss');
        ad.dispose();
        _appOpenAd = null;
      },
    );
    _appOpenAd?.show();
  }
}
